//
//  ViewController3.swift
//  SWIFTLEARN
//
//  Created by chichaojituan521 on 2017/5/12.
//  Copyright © 2017年 linch. All rights reserved.
//

import UIKit
import WebKit
class ViewController3: UIViewController,UITableViewDelegate,UITableViewDataSource {
    //表的数组
    var tableArray:[String]?

    //倒计时
    var  ctimer:UIDatePicker!
    var btnstart:UIButton!
    var leftTime:Int = 180
    var alertController:UIAlertController!
    var timer:Timer!
    //
    let pageWidth = Int(UIScreen.main.bounds.width)
    let pageHeight = Int(UIScreen.main.bounds.height) - 64
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.orange

        let btnName:[String] = ["倒计时","WKWebView","UIToolbar","UITableVeiw","UIAlertController","ScoreView","Animation","0","0","0","0","退出"]
        
        let btnInterval: Int = 10
        
        let btnWidth = (self.view.frame.size.width - CGFloat(btnInterval) * 5)/4.0
        
        
        for btnitem in 1...12 {
            
            let item = btnitem - 1
            
            let button = UIButton(type: .custom)
            button.tag = btnitem
            
            self.view?.addSubview(button)
            
            button.setTitle(btnName[item], for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
            button.titleLabel?.lineBreakMode = .byWordWrapping
            button.backgroundColor = UIColor.orange
            
            let btncgx = btnInterval + (Int(item) % 4) * (Int(btnWidth) + btnInterval)
            let btncgy = 74 + (Int(item) / 4) * (btnInterval + 50)
            button.frame = CGRect(x:btncgx , y:btncgy , width: Int(btnWidth), height: 50)
            
            button.addTarget(self, action: #selector(buttonClickMethod(_:)),for: .touchUpInside)
            
        }
    }

    func buttonClickMethod(_ button:UIButton) {
        
        switch button.tag {
        case 1:
            self.timeIsComingMethod()
        case 2:
            self.UIWebViewMethod()
        case 3:
            self.UIToolbarMethod()
        case 4:
            self.UITableVeiwMethod()
        case 5:
            self.UIAlertControllerMethod()
        case 6:
            self.ScoreViewMethod()
        case 7:
            self.AnimationMethod()
//        case 8:
//            self.UIstepperMethod()
//        case 9:
//            self.UIScrollViewMethod()
//        case 10:
//            self.UIGestureRecognizerMethod()
//        case 11:
//            self.UIDatePickerMethod()
        case 12:
            self.PopVCMethod()
            
        default:
            print("case===")
        }
    }
    
    func PopVCMethod() {
        self.dismiss(animated: true) {
            
        }
    }
    //MARK:- 倒计时
    func timeIsComingMethod () {
        
       
        
        
        ctimer = UIDatePicker(frame:CGRect(x:50, y:120, width:200, height:200))
        self.ctimer.datePickerMode = UIDatePickerMode.countDownTimer
        
        //必须为 60 的整数倍，比如设置为100，值自动变为 60
        self.ctimer.countDownDuration = TimeInterval(leftTime)
        ctimer.addTarget(self, action: #selector(timerChanged),
                         for: .valueChanged)
        
        self.view.addSubview(ctimer)
        
        btnstart =  UIButton(type: .system)
        btnstart.frame = CGRect(x:100, y:400, width:100, height:100)
        btnstart.setTitleColor(UIColor.red, for: .normal)
        btnstart.setTitleColor(UIColor.green, for:.disabled)
        btnstart.setTitle("开始", for:.normal)
        btnstart.setTitle("倒计时中", for:.disabled)
        
        btnstart.clipsToBounds = true
        btnstart.layer.cornerRadius = 5
        btnstart.addTarget(self, action:#selector(startClicked),
                           for:.touchUpInside)
        
        self.view.addSubview(btnstart)
        
        
        
    }
    
    func timerChanged()
    {
        print("您选择倒计时间为：\(self.ctimer.countDownDuration)")
    }
    func startClicked(sender:UIButton)
    {
        self.btnstart.isEnabled = false
        
        // 获取该倒计时器的剩余时间
        leftTime = Int(self.ctimer.countDownDuration)
        // 禁用UIDatePicker控件和按钮
        self.ctimer.isEnabled = false
        
        // 创建一个UIAlertController对象（警告框），并确认，倒计时开始
        alertController = UIAlertController(title: "系统提示",
                                            message: "倒计时开始，还有 \(leftTime) 秒...",
            preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)
        // 显示UIAlertController组件
        self.present(alertController, animated: true, completion: nil)
        
        // 启用计时器，控制每秒执行一次tickDown方法
        timer = Timer.scheduledTimer(timeInterval: TimeInterval(1), target:self,
                                     selector:#selector(tickDown),
                                     userInfo:nil,repeats:true)
    }
    
    /**
     *计时器每秒触发事件
     **/
    func tickDown()
    {
        alertController.message = "倒计时开始，还有 \(leftTime) 秒..."
        // 将剩余时间减少1秒
        leftTime -= 1
        // 修改UIDatePicker的剩余时间
        self.ctimer.countDownDuration = TimeInterval(leftTime)
        print(leftTime)
        // 如果剩余时间小于等于0
        if(leftTime <= 0)
        {
            // 取消定时器
            timer.invalidate()
            // 启用UIDatePicker控件和按钮
            self.ctimer.isEnabled = true
            self.btnstart.isEnabled = true
            alertController.message = "时间到！"
        }
    }
    //MARK: UIWebView
    func UIWebViewMethod () {
        
        let webView = WKWebView(frame: CGRect(x: 0, y: 230, width: pageWidth, height: pageHeight - 150))
        //____________________________________ //在 UIWebView 中显示 HTML 内容
//        let html = "<h1>欢迎来到：<a href='http://hangge.com'>航歌</a></h1>"
//        webView.loadHTMLString(html,baseURL:nil)
        
        //_____________________________________//在 UIWebView 中显示 PDF
        
//        let path = Bundle.main.path(forResource: "Apple_Developer_Program_License_Agreement_20170227", ofType:"pdf")
//        let urlStr = URL.init(fileURLWithPath: path!)
//        print(urlStr)
//        webView.load(URLRequest(url:urlStr))

        //____________________________________//在 UIWebView 中显示 PDF, 但是是通过 loadData 方式加载
//        let path2 = Bundle.main.path(forResource: "Apple_Developer_Program_License_Agreement_20170227", ofType:"pdf")
//        let urlStr2 = URL.init(fileURLWithPath: path2!)
//        let data = try! Data(contentsOf: urlStr2)
//        webView.load(data, mimeType: "application/pdf", characterEncodingName: "utf-8",
//                     baseURL: NSURL() as URL)
        

        //____________________________________//在 加载网页, 但是是通过 loadData 方式加载
        let urlStr3 = URL(string: "https://www.baidu.com/")
        webView.load(URLRequest(url:urlStr3!))
        
        self.view.addSubview(webView)
        
        
        
    }
    func UIToolbarMethod()
    {
        let browserToolbar = UIToolbar(frame:CGRect(x: 50, y: 300, width: 300, height: 50))
        self.view.addSubview(browserToolbar)
        
//        let backBtn = UIBarButtonItem(image: UIImage(named:"2222.png"), style: .plain, target: self, action: #selector(goToBack(_:)))
        
        let backBtn =  UIBarButtonItem(image:UIImage(named:"2222.png"),
                                       landscapeImagePhone:UIImage(named:"2222.png"),
                                       style:.plain, target:self,
                                       action:#selector(goToBack(_:)))
        
        let forwardBtn = UIBarButtonItem(image: UIImage(named:"11111.png"), style: .plain, target: self, action: #selector(goToFace))
        browserToolbar.setItems([backBtn,forwardBtn], animated: true)
    }
    func goToBack(_ sender:UIBarButtonItem) {
        print("back")
    }
    func goToFace() {
        print("face")
    }
    //MARK:- 表
    func UITableVeiwMethod () {
        
        self.tableArray = ["倒计时","WKWebView","UIToolbar","UITableVeiw","six","seven","eight","nine","ten","eleven","twife","last"]

        let tableView = UITableView(frame: CGRect(x: 50, y: 300, width: 300, height: 300))
        self.view.addSubview(tableView)
        tableView.backgroundColor = UIColor.lightGray
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "swiftcell")
        
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (tableArray?.count)!
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "swiftcell", for: indexPath)
        cell.textLabel?.text = tableArray?[indexPath.row]
        
        return cell
        
    }
    func tableView(_ tableView: UITableView,
                   commit editingStyle: UITableViewCellEditingStyle,
                   forRowAt indexPath: IndexPath) {
        print("删除\(indexPath.row)")
        let index = indexPath.row
        self.tableArray?.remove(at: index)
        tableView.deleteRows(at: [indexPath],
                                   with: .top)
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath)
        -> UITableViewCellEditingStyle {
            
            return UITableViewCellEditingStyle.delete
    }
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "不要你了"
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("点击了-----\(indexPath.row)")
    }
    
    
    func UIAlertControllerMethod () {
        
        let alert = UIAlertController(title: "提示", message: "你要离开了吗", preferredStyle: .alert)
        
        let cancleBtn = UIAlertAction(title: "no", style: .cancel, handler: nil)
        let okBtn = UIAlertAction(title: "ok", style: .default) { action  in
            let tf = alert.textFields?.first
            print("ok  了===\(String(describing: tf?.text))")
        }
        alert.addTextField { (textField:UITextField) ->Void in
            textField.placeholder = "username"
            
        }
        
        alert.addAction(okBtn)
        alert.addAction(cancleBtn)
       
        self.present(alert, animated: true, completion: nil)
        
        //自动消失
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2){
            self.presentedViewController?.dismiss(animated: true, completion: nil)
        }
        
        
    }
    //MARK:
    func ScoreViewMethod(){
        
        
        let commenScore = ScoreView(type: .commen)
        commenScore.frame.origin = CGPoint(x:50, y:280)
//        commenScore.changeScore(value: 0)
        commenScore.score = 1234
        self.view.addSubview(commenScore)
        
        let bestScore = ScoreView(type: .best)
        bestScore.frame.origin = CGPoint(x:170, y:280)
//        bestScore.changeScore(value: 123)
        bestScore.score = 123
        self.view.addSubview(bestScore)
        
        
        
    }
    
    func AnimationMethod (){
        var dimension:Int = 4
        //数字格子的宽度
        var width:CGFloat = 50
        //格子与格子的间距
        var padding:CGFloat = 6
        var backArr = Array<UIView>()
        
        
        var x:CGFloat = 50
        var y:CGFloat = 150
        
        for i in 0..<dimension {
            
            for j in 0..<dimension {
                let background = UIView(frame:CGRect(x: x, y: y, width: width, height: width))
                background.backgroundColor = UIColor.red
                self.view.addSubview(background)
                //将视图保存起来，以备后用
                backArr.append(background)
                x += padding + width
            }
            y += padding + width
        }
        
        
        
    }
}
